#include "Protocol.hpp"
#include "Socket.hpp"
#include <time.h>
#include <unistd.h>

static void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << " ip port\n" << std::endl; 
}

// ./ClientCal ip port
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    string ip = argv[1];
    uint16_t port = stoi(argv[2]);

    Socket s;
    s.Connect(ip,port);

    srand(time(NULL));
    
    string oper = "+-*/%&$^";

    while(true)
    {
        sleep(1);

        int left = rand()%100 + 1;
        int right = rand()%100;
        char op = oper[rand()%(oper.size())];

        Request rst(left,right,op);
        string content;
        bool res = rst.Serialize(&content);
        // if(!res)
        // {

        // }
        content = Encode(content);

        write(s._sockfd,content.c_str(),content.size());

        string inbuffer_stream;
        char buffer[1024];
        read(s._sockfd,buffer,sizeof(buffer));
        inbuffer_stream += buffer;
        res = Decode(inbuffer_stream,&content);
        if(!res)
        {
            continue;
        }

        Response rse;
        res = rse.Deserialize(content);
        if(!res)
        {
            cout<<"结果报文的核心数据格式出错！！！"<<endl;
            continue;
        }

        cout<<"计算成功，结果是 result:"<<rse._result<<"code:"<<rse._code<<endl;

    }
    
    return 0;
}